<?php

class tWebsetup_Synchronize extends tStandard_Treeitem
{

	public $physic = false;
	
	function save() 
	{
		if (!$this->cms->user->isAdmin) throw new cException('Na tuto akci potřebujete administrátorská práva.');
		
		//synchronizace	
		$query = $this->getCustom('query');
		$query = explode('CREATE TABLE ',' '.$query);
		$succ = true;
		
		foreach ($query as $k=>$q)
		{
			if ($k>0)
			$succ = $succ AND $this->synchronizeTables('CREATE TABLE '.$q);
		}
		if (!$succ) { /*..*/ }
	}
	
	function synchronizeTables($q) 
	{
    	$query=null;
    	$rows=explode("\n",$q);
		unset($rows[(count($rows)-1)]);
		unset($rows[(count($rows)-1)]);
		unset($rows[0]);
		
		// get table name
		preg_match('/CREATE TABLE [`]?([^` ]+)[`]?/', $q, $matches);
		$table = $matches[1];

		$r=mysql_query("SHOW COLUMNS FROM ".$table);
		while ($c=mysql_fetch_array($r)) {
			$dbColumns[]=$c[0];
		}
		
		//If table doesn't exist
		if (count($dbColumns)==0) 
		{
			$this->cms->tree->query($q);
		}
		
		foreach ($rows as $k=>$r) 
		{
			$parts=explode("`",$r);
			$column[$k]=$parts[1];
			if (!in_array($column[$k],$dbColumns)) 
			{
				if ($r[strlen($r)-2]==",") { $m=substr($r,0,-2); } else $m=substr($r,0,-1);
				if ($column[($k-1)]<>"") { $m.=" AFTER `".$column[($k-1)]."`"; }
				$missing[]=$m;
			}
			unset($m);
		}
		if (is_array($missing)) 
		{
			foreach ($missing as $m) 
			{
				$query.="ALTER TABLE ".$table." ADD $m;\n\n\n";
			}
			return $this->cms->tree->query($query);
		} else return true;
	}
}

?>